package com.doupi.partner.manager.authenticator.tag;

import com.doupi.partner.manager.authenticator.util.PermissionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.tags.PermissionTag;

/**
 * 逻辑匹配权限标签
 * 
 * 支持or and not 关键词 不支持and or 混用
 * 
 * <shiro:hasPermission name="showcase:tree:create or showcase:tree:update or showcase:tree:delete">
 * 
 * @author Alvin Wang
 * @version 1.0.0 @ 2017-04-16
 */
public class LogicPermissionTag extends PermissionTag {
	private static final String OR_OPERATOR = " or ";
	private static final String AND_OPERATOR = " and ";
	private static final String NOT_OPERATOR = "!";

	@Override
	protected boolean isPermitted(String permission) {
		if (StringUtils.contains(permission, OR_OPERATOR)) {
			String[] permissions = StringUtils.splitByWholeSeparator(permission, OR_OPERATOR);
			for (String orPermission : permissions) {
				if (isPermittedWithNotOperator(orPermission)) {
					return true;
				}
			}
			return false;
		} else
			if (StringUtils.contains(permission, AND_OPERATOR)) {
				String[] permissions = StringUtils.splitByWholeSeparator(permission, AND_OPERATOR);
				for (String orPermission : permissions) {
					if (!isPermittedWithNotOperator(orPermission)) {
						return false;
					}
				}
				return true;
			} else {
				return isPermittedWithNotOperator(permission);
			}
	}

	private boolean isPermittedWithNotOperator(String permission) {
		if (StringUtils.startsWith(permission, NOT_OPERATOR)) {
			return !PermissionUtils.checkWholePermissionString(StringUtils.substringAfter(permission, NOT_OPERATOR));
		} else {
			return PermissionUtils.checkWholePermissionString(permission);
		}
	}

	@Override
	protected boolean showTagBody(String p) {
		return isPermitted(p);
	}
}
